package com.wj;

import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.Phonenumber;

import java.util.List;

/**
 * @author jun.wang
 * @title: PhoneNumberUtil
 * @projectName ownerpro
 * @description: TODO
 * @date 2019/9/20 14:29
 */
public class PhoneNumberUtil {

    public final static List<PhoneNumber> phoneNumberList = FileUtil.read();

    /**
     * 根据国家码判断电话号码的有效性
     * @param phoneNo
     * @param countryCode
     * @return
     */
    public static boolean isPhoneNumberValid(String phoneNo, String countryCode) {
        com.google.i18n.phonenumbers.PhoneNumberUtil phoneUtil = com.google.i18n.phonenumbers.PhoneNumberUtil.getInstance();
        try {
            Phonenumber.PhoneNumber numberProto = phoneUtil.parse(phoneNo, countryCode);
            return phoneUtil.isValidNumber(numberProto);
        } catch (NumberParseException e) {
            return false;
            //throw new RuntimeException("isPhoneNumberValid NumberParseException was thrown", e);
        }
    }

    /**
     * 根据电话代码判断有效性
     * @param phoneNo
     * @param phoneCode
     * @return
     */
    public static boolean PhoneNumberValidPhoneCode(String phoneNo, String phoneCode) {
        com.google.i18n.phonenumbers.PhoneNumberUtil phoneUtil = com.google.i18n.phonenumbers.PhoneNumberUtil.getInstance();
        String countryCode = "";
        if (phoneNumberList == null || phoneNumberList.size() == 0) {
            return false;
        }
        for (PhoneNumber phoneNumber: phoneNumberList) {
            if (phoneCode.equals(phoneNumber.getPhoneCode())) {
                countryCode = phoneNumber.getCountryCode();
            }
        }
        if ("".equals(countryCode)) {
            return false;
        }
        try {
            Phonenumber.PhoneNumber numberProto = phoneUtil.parse(phoneNo, countryCode);
            return phoneUtil.isValidNumber(numberProto);
        } catch (NumberParseException e) {
            return false;
            //throw new RuntimeException("isPhoneNumberValid NumberParseException was thrown", e);
        }
    }


    public static void main(String args[]) {
        String phone = "66413982";
        String countryCode = "CN";
        System.out.println(PhoneNumberValidPhoneCode(phone, "65"));
    }
}
